package com.RPC;

import com.one2many.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class RPCServer {

    public static String RPC_QUEUE_NAME = "rpc_queue";
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        final Channel channel = connection.createChannel(1);
        channel.queueDeclare(RPC_QUEUE_NAME,false,false,false,null);
        channel.basicQos(1);
        Consumer consumer = new DefaultConsumer(channel){
          @Override
          public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
              super.handleDelivery(consumerTag,envelope,properties,body);
              String mes = new String(body, "UTF-8");
              int num = Integer.valueOf(mes);
              System.out.println("接收数据：" + num);
              //AMQP.BasicProperties properties1 = new AMQP.BasicProperties.Builder().correlationId(properties.getCorrelationId()).build();
              num = fib(num);
              //将处理结果(响应)发送到回调队列
              channel.basicPublish("", properties.getReplyTo(), properties, String.valueOf(num).getBytes());
              //如果消费者遇到情况(its channel is closed, connection is closed, or TCP connection is lost)挂掉了，那么，RabbitMQ会重新将该任务添加到队列中。
              channel.basicAck(envelope.getDeliveryTag(), false);
          }
        };
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        while (true) {
            synchronized (consumer) {
                try {
                    consumer.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /*
        获取斐波那契数列的第n个值得大小
     */
    private static int fib(int n) {
        System.out.println(n);
        if (n == 0)
            return 0;
        if (n == 1)
            return 1;
        return fib(n - 1) + fib(n - 2);
    }
}
